<template>
  <div class="main">
    <section>
      <el-form class="section" :model="formData" :rules="formRules" size="medium" ref="form" label-width="100px">
        <div class="block-header"><div>基础信息</div></div>
        <el-form-item label="活动名称:" prop="promotionName">
          <el-input v-model="formData.promotionName" :disabled="limitEdit" placeholder="如：五一满减活动，最多20字"></el-input>
        </el-form-item>
        <el-form-item label="活动时间:" prop="dateTimeRange">
          <el-date-picker
            v-model="formData.dateTimeRange"
            type="datetimerange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动说明:" prop="promotionExplain">
          <el-input v-if="!formData.promotionExplain && limitEdit" :disabled="limitEdit" placeholder=""></el-input>
          <el-input v-else v-model="formData.promotionExplain" :disabled="limitEdit" placeholder="最多二十字"></el-input>
        </el-form-item>
        <div class="block-header"><div>商品信息</div></div>
        <el-form-item label="活动商品:">
          <el-button type="primary" icon="el-icon-plus" size="small" class="filter-item" @click="chooseGoods">添加商品</el-button>
          <el-table :data="formData.fullCutGoodsDtos" border>
            <!--<el-table-column align="center" label="商品图片" min-width="100">-->
              <!--<template slot-scope="scope">-->
                <!--<img class="img" :src="scope.row.imgUrl" />-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
            <el-table-column align="center" label="商品ID" prop="goodsId" min-width="80"></el-table-column>
            <el-table-column align="center" label="商品名称" prop="goodsName" min-width="100"></el-table-column>
            <el-table-column align="center" label="商品类型" prop="goodsType" min-width="100">
              <template slot-scope="scope">
                {{scope.row.goodsType === 1 ? '单品' : '套餐'}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品销量" prop="salesVolume" min-width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.salesVolume" style="width:80px"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="100">
              <template slot-scope="scope">
                <el-button type="danger" @click="del(scope.row, scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="success" icon="el-icon-plus" size="small" class="filter-item-package" @click="chooseGoodsPackage" plain>添加套餐</el-button>
          <el-table :data="formData.fullCutPackageDtos" border highlight-current-row>
            <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
            <el-table-column align="center" min-width="80" label="套餐款号" prop="goodsId"></el-table-column>
            <el-table-column align="center" min-width="100" label="套餐名称" prop="goodsName"></el-table-column>
            <el-table-column align="center" min-width="100" label="套餐类型">
              <template slot-scope="scope">
                {{scope.row.packType === 1 ? '固定模式' : scope.row.packType === 2 ? '自由组合模式' : '城市合伙人套餐'}}
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="100" label="套餐销量" prop="salesVolume">
              <template slot-scope="scope">
                <el-input v-model="scope.row.salesVolume" style="width:80px"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="removeTempPackageSelect(scope.row)">移除</el-button>
                </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <div v-for="(item, index) in formData.fullCutConditionDtos" :key="index" :name="index">
          <div class="block-header"><div>优惠设置</div> <small>提醒：每级优惠不叠加，如：满足二级优惠条件后则不再享有一级优惠。最多支持五级优惠。</small></div>
          <!--<el-form-item label="优惠类型:" prop="promotionType">-->
              <!--<el-radio v-for="(item, index) in types" v-model="formData.promotionType" :label="item.val" :key="index"  :disabled="limitEdit">{{item.name}}</el-radio>-->
          <!--</el-form-item>-->
          <el-form-item label="优惠类型:" v-if="formData.fullCutConditionDtos.length < 2" :prop="`fullCutConditionDtos[${index}].promotionType`">
            <el-radio v-for="(i, ikey) in types" v-model="item.promotionType" :label="i.val" :key="ikey"  :disabled="limitEdit">{{i.name}}</el-radio>
          </el-form-item>
          <el-form-item label="优惠门槛:" :prop="`fullCutConditionDtos[${index}].discountsLevel`" :rules="formRules.fullCutConditionDtos.discountsLevel">
            活动商品总额满<el-input class="money" v-model="item.discountsLevel"  :disabled="limitEdit"></el-input>元
          </el-form-item>
          <el-form-item label="优惠内容:" :prop="`fullCutConditionDtos[${index}].discountsContent`" :rules="formRules.fullCutConditionDtos.discountsContent">
            订单金额立减<el-input class="money" v-model="item.discountsContent" :disabled="limitEdit"> <template slot="append">元</template></el-input>
          </el-form-item>
          <el-form-item prop="highestMultiple" v-if="formData.fullCutConditionDtos.length < 2">
              <el-checkbox v-model="formData.isOverlay" true-label="1" false-label="0" :disabled="limitEdit">是否叠加</el-checkbox>
              <div v-if="formData.isOverlay*1">叠加最高倍数<el-input class="money" v-model="formData.highestMultiple" max="10" :disabled="limitEdit"> <template slot="append">倍</template></el-input></div>
          </el-form-item>
          <el-form-item label="优惠说明:" :prop="`fullCutConditionDtos[${index}].remark`">
            <el-input v-if="!item.remark && limitEdit" :disabled="limitEdit" placeholder=""></el-input>
            <el-input v-else v-model="item.remark" :disabled="limitEdit" placeholder="说明字数限制十五个字啊十五个"></el-input>
          </el-form-item>
          <el-form-item v-if="formData.fullCutConditionDtos.length > 1">
              <el-button :disabled="limitEdit" @click="deleteLine(index)">删除</el-button>
          </el-form-item>
        </div>
        <el-form-item> <span class="newLine" :class="{'no': Number(formData.isOverlay) === 1}" @click="addNewLine">添加新优惠</span> </el-form-item>

        <el-form-item v-if="showSave">
          <el-button type="success" :loading="btnLoading" @click="save">保存</el-button>
        </el-form-item>

      </el-form>
    </section>
  </div>
</template>

<script>
  import { createNewFullReduce, editFullReduce, goodsCheck } from '@/api/activity/fullReduce'
  import {regexp} from '@/utils/tools'
  import treeToArray from '@/components/TreeTable/eval'
  export default {
    name: "edit",
    data() {
      var checkMultiple = (rule, value, callback) => {
        if (this.formData.isOverlay * 1 && !value) {
          callback(new Error('倍数不能为空'));
        }
        setTimeout(() => {
            if (value > 10) {
              callback(new Error('最高倍数不能超过10'));
            } else {
              callback();
            }
        }, 500);
      };
      return {
        limitEdit: false,
        showSave: true,
        deleteIds: [],
        categoryTree: [],
        categoryLoading: true,
        btnLoading: false,
        formRules: {
          promotionName: [
            {required: true, message: '不能为空', trigger: 'change'},
            {max: 20, message: '不能超过20字符', trigger: 'change'},
          ],
          dateTimeRange: [{ required: true, message: '不能为空', trigger: 'change' }],
          promotionExplain: [
            {max: 20, message: '不能超过20字符', trigger: 'change'}
          ],
          promotionType: [
            { required: true, message: '不能为空', trigger: 'change' }
          ],
          highestMultiple: [
            { pattern: regexp.sort, message: '必须为1-999的正整数', trigger: 'change'},
            { validator: checkMultiple, trigger: 'change' }
          ],
          fullCutConditionDtos: {
            discountsLevel: [
              { required: true, message: '不能为空', trigger: 'change' },
              {pattern: regexp.sort, message: '必须为1-999的正整数', trigger: 'change'}],
            discountsContent: [
              { required: true, message: '不能为空', trigger: 'change' },
              { pattern: regexp.sort, message: '必须为1-999的正整数', trigger: 'change'}],
            remark: [
              {max: 15, message: '不能超过15字符', trigger: 'change'}]
          }
        },
        types: [
          { name: '满减', val: 1},
          // { name: '满赠', val: 2}
        ],
        formData: {
          promotionType: 1,
          fullCutGoodsDtos: [],
          fullCutPackageDtos: [],
          isOverlay: 0,
          fullCutConditionDtos: [{
            promotionType: 1,
            discountsLevel: '',
            discountsContent: '',
            remark: ''
          }]
        }
      }
    },
    created() {
      let pageName = this.$route.name
      let storage
      let res
      switch (pageName) {
        case 'fullReduceView':
          storage = JSON.parse(sessionStorage.getItem('_full_reduce_item_'))
          // 参数回填
          res = {
            ...storage,
            dateTimeRange: [storage.startTime, storage.endTime]
          }
          res.isOverlay = res.isOverlay + ''
          this.formData = res
          this.showSave = false
          break
        case 'fullReduceEdit':
          storage = JSON.parse(sessionStorage.getItem('_full_reduce_edit_'))
          if(storage.status === 2) {
            this.limitEdit = true
          }
          // 二期删除，仅供一期使用
          storage.fullCutConditionDtos.map(item => {
            return item.promotionType = 1
          })
          // 参数回填
          res = {
            ...storage,
            dateTimeRange: [storage.startTime, storage.endTime]
          }
          res.isOverlay = res.isOverlay + ''
          this.formData = res
          break
        default: ''
      }
    },
    methods: {
      getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
      },
      save() {
        this.$refs['form'].validate((valid) => {
           if (!valid) { return }
          let dateTimeRange = this.formData.dateTimeRange;
          if (dateTimeRange && dateTimeRange.length > 0) {
            this.formData.startTime = dateTimeRange[0];
            this.formData.endTime = dateTimeRange[1];
          }
          let pageName = this.$route.name
          if (pageName === 'fullReduceEdit') {
            editFullReduce(this.formData).then(res => {
              this.$message.success('编辑完成')
              setTimeout(() => { this.$router.push({name: 'fullReduce'}) }, 500)
            })
          } else {
          // 新建
            this.formData.fullCutStatus = 1
            createNewFullReduce(this.formData).then(res => {
              this.$message.success('活动新建成功')
              setTimeout(() => { this.$router.push({name: 'fullReduce'}) }, 500)
            }).catch(e => {
              // this.$message.error('新建失败，请重试')
            })
          }
        })
      },
      deleteLine(val) {
        this.formData.fullCutConditionDtos.splice(val, 1)
      },
      addNewLine() {
        if (this.formData.isOverlay*1 === 1 || this.limitEdit || this.formData.fullCutConditionDtos.length >= 5) { return }
        this.formData.fullCutConditionDtos.push({
          promotionType: 1,
          discountsLevel: '',
          discountsContent: '',
          remark: ''
        })
      },

      // 移除套餐
      del(item, index) {
        this.formData.fullCutGoodsDtos.splice(index, 1)
      },
      // 选择商品
      async chooseGoods(){
        let idList = []
        let goods= this.formData.fullCutGoodsDtos.map(i => {
          idList.push(i.goodsId)
          return {
            price: i.price,
            regionPrice: i.regionPrice,
            marketValue: i.marketValue,
            directorPrice: i.directorPrice,
            image: i.imgUrl,
            goodsId: i.goodsId,
            name: i.goodsName,
            goodsType: i.goodsType,
            categoryId: i.categoryId,
            salesVolume: i.salesVolume
          }
        })
        this.goodsChoose({}, goods).then(val => {
          let goodsList = []
          let arr = []
          val.forEach(item => {

            // 返回一级分类id及其名称
            // let id = 0
            // this.categoryTree.map(item => {
            //   // 当id相等
            //   if(val.categoryId === item.id) {
            //     // 父id为0 则为一级分类
            //     if (item.parentId === 0) {
            //       id = item.id
            //     } else {
            //       id = item.parentId
            //     }
            //   }
            // })
            const params = {
              activityId: item.activityId || '',
              commission:  '',
              fromType: item.fromType || '',
              maximumCommission:  '',
              packType: item.packType || '',
              price: item.price || '',
              regionPrice:  '',
              marketValue: '',
              directorPrice: '',
              imgUrl: item.image || '',
              goodsId: item.goodsId || '',
              goodsName: item.name || '',
              goodsType: item.goodsType || '',
              categoryId: item.parentCategoryId || ''
            }
            if(item.salesVolume) {
              params.salesVolume = item.salesVolume
            } else {
              const num = this.getRndInteger(100, 5000)
              params.salesVolume = num
            }
            goodsList.push(params)
          })
          goodsList.forEach(async item => {
            if (!idList.includes(item.goodsId)) {
              const param = {
                id: item.goodsId,
                checkList: [1, 2, 3, 4], // 互斥类型
                goodsType: 1
              }
              const res = await goodsCheck(param)
              if (res.status*1 === 200) { arr.push(item) }
            } else {
              arr.push(item)
            }
          })
          // console.log('goodsList', goodsList)
          // console.log('arr', arr)
          this.formData.fullCutGoodsDtos = arr
        }).catch(err => {
          this.formData.fullCutGoodsDtos = []
        })
      },
      chooseGoodsPackage () {
        let idList = []
        let selected = this.formData.fullCutPackageDtos.map(item => {
          idList.push(item.goodsId)
          return {
            price: item.price,
            regionPrice: item.regionPrice,
            marketValue: item.marketValue,
            directorPrice: item.directorPrice,
            image: item.imgUrl,
            packageId: item.goodsId,
            name: item.goodsName,
            type: item.packType,
            salesVolume: item.salesVolume
          }
        });
        this.packageChoose({}, selected).then(val => {
          let goodsList = []
          let arr = []
          val.forEach(item => {
            const params = {
              price: item.price || '',
              regionPrice: item.regionPrice || '',
              marketValue: item.marketValue || '',
              directorPrice: item.directorPrice || '',
              imgUrl: item.image || '',
              goodsId: item.packageId,
              goodsName: item.name,
              packType: item.type,
              salesVolume: item.salesVolume ? item.salesVolume : Math.floor(Math.random() * (5000 - 1000)) + 1000,
              goodsType: 2,
              from_type: 3
            }
            goodsList.push(params)
          })
          goodsList.forEach(async item => {
            if (!idList.includes(item.goodsId)) {
              const param = {
                id: item.goodsId,
                checkList: [1, 2, 3, 4], // 互斥类型
                goodsType: 2
              }
              const res = await goodsCheck(param)
              if (res.status*1 === 200) { arr.push(item) }
            } else {
              arr.push(item)
            }
          })
          this.formData.fullCutPackageDtos = arr
        });
      },
      removeTempPackageSelect(item) {
        this.$confirm(`确定要删除 ${item.goodsName} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.formData.fullCutPackageDtos.splice(this.formData.fullCutPackageDtos.indexOf(item), 1)
        }).catch(err => {
          console.log(err);
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
.block-header {
  display: flex;
  color: #1ea0ff;
  font-size: 14px;
  padding: 12px 0;
  margin-bottom: 12px;
  background: #f7f7f7;
  align-items: center;
  &>div{
    padding: 0 12px;
    border-left: 2px solid #1ea0ff;
  }
  small {
    color: #666!important;
    font-size: 12px;
  }
}
  .money {
    width: 200px;
    margin: 0 20px;
  }
  .filter-item { margin-bottom: 20px }
  .filter-item-package { margin: 10px 0 20px 0; }
  .img { max-height: 90px }
  .newLine {
    color: #09f;
    cursor: pointer;

    &.no {
      color: #f5f5f5!important;
      font-weight: bold!important;
      cursor: text;
    }

  }
</style>
